import { Ref, isRef } from 'vue'
import { isNil } from 'lodash-es'

export const isServer = typeof window === 'undefined'

export const refToRaw = <T>(value: Ref<T> | T) => {
  return isRef(value) ? value.value : value
}

export const isDocumentVisibility = () => {
  if (isServer || isNil(window.document?.visibilityState)) return true
  return window.document.visibilityState === 'visible'
}

export const limitTrigger = (fn: any, timeInterval: number) => {
  let running = false

  return (...args: any[]) => {
    if (running) return

    running = true
    fn(...args)
    setTimeout(() => {
      running = false
    }, timeInterval)
  }
}

export const get = (source: Record<string, any>, path: string, defaultValue?: any) => {
  const paths = path.split('.')
  let result = source

  for (const p of paths) {
    result = Object(result)[p]
    if (result === undefined) {
      return defaultValue
    }
  }
  return result
}
